package com.saicmotor.hk2.controller;

import com.saicmotor.hk2.model.Role;
import com.saicmotor.hk2.model.User;
import com.saicmotor.hk2.service.CommonService;
import com.saicmotor.hk2.service.RoleService;
import com.saicmotor.hk2.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleService roleService;
    @Autowired
    CommonService commonService;
    @Autowired
    UserRoleService userRoleService;

    @RequestMapping("/all")
    public List<Role> getAll() {
        return roleService.getAll();
    }

    @RequestMapping("/add")
    public String insertInfoOfRole(String name) { //http://localhost:8080/user/info?name=setName&age=setAge
        if (commonService.checkName("role", name)) {
            return name + " has EXISTED";
        } else {
            roleService.insertRoleInfo(name);
            return "Insert [" + name + "] Complete";
        }
    }

    @RequestMapping(value = "/delete")
    public String deleteUser(String name) {
        roleService.deleteByName(name);
        userRoleService.deleteByRoleName(name);
        return "Delete [" + name + "] Complete";
    }

    @RequestMapping("/update")
    public String updateAgeOfUser(String newName,String oldName) {
        if (!commonService.checkName("role", oldName)) {
            return oldName + " is NOT EXIST";
        } else if (commonService.checkName("role", newName)) {
            return newName + " has EXISTED";
        } else {
            roleService.updateName(newName, oldName);
            return "Update [" + oldName + "] Complete";
        }
    }

    @RequestMapping("/create")
    public String RoleTableCreation() {
        if (commonService.checkTable("role")) {
            return "\"role\" Table Exists";
        } else {
            roleService.createRoleTable("role");
            return "Create \"role\" Table Complete";
        }
    }
}
